//
//  UIButton+Extension.swift
//  SwiiftProject
//
//  Created by Apple on 2019/5/15.
//  Copyright © 2019 lazyloading. All rights reserved.
//

import Foundation
import UIKit

fileprivate var codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())

typealias start = (UIButton)->Void;
typealias change = (UIButton, Int)->Void;
typealias finish = (UIButton)->Void;
typealias cancel = (UIButton)->Void;

extension UIButton {
    
    
    /// 开始倒计时
    ///
    /// - Parameters:
    ///   - count: 倒计时
    ///   - start: 开始
    ///   - change: 变化
    ///   - finish: 完成
    func startCountDown(_ count: Int, start : start? = nil, change :  change? = nil, finish : finish? = nil){
        isEnabled = false
        if (start != nil){
            start!(self);
        }
        
        var remainingCount : Int = count {
            
            willSet {
                setTitle("\(newValue)秒重发", for: .normal)
                if (change != nil){
                    change!(self,newValue);
                }
                if newValue <= 0 {
                    
                    setTitle("获取验证码", for: .normal)
                    if (finish != nil){
                        finish!(self);
                    }
                }
            }
        }
        
        if codeTimer.isCancelled {
            codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
        }
        codeTimer.schedule(deadline: .now(), repeating: .seconds(1))
        
        codeTimer.setEventHandler(handler: {
            DispatchQueue.main.async {
                remainingCount -= 1
                if remainingCount <= 0 {
                    self.isEnabled = true
                    codeTimer.cancel()
                }
            }
        })
        codeTimer.resume()
    }
    
    
    /// 取消倒计时
    ///
    /// - Parameter cancel: 取消
    func CancelCountDown(cancel : cancel? = nil) {
        
        if !codeTimer.isCancelled {
            codeTimer.cancel()
        }
        
        DispatchQueue.main.async {
            
            self.isEnabled = true
            if self.titleLabel?.text?.count != 0 {
                self.setTitle("获取验证码", for: .normal)
            }
        }
    }
    
}
